<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Leetcode 题解 - 位运算 | Zhang Shuo'blog</title><meta name="keywords" content="Leetcode题解"><meta name="author" content="Zhang Shuo"><meta name="copyright" content="Zhang Shuo"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Leetcode 题解 - 位运算  Leetcode 题解 - 位运算 0. 原理 1. 统计两个数的二进制表示有多少位不同 2. 数组中唯一一个不重复的元素 3. 找出数组中缺失的那个数 4. 数组中不重复的两个元素 5. 翻转一个数的比特位 6. 不用额外变量交换两个整数 7. 判断一个数是不是 2 的 n 次方 8.  判断一个数是不是 4 的 n 次方 9. 判断一个数的位级表示是否不会">
<meta property="og:type" content="article">
<meta property="og:title" content="Leetcode 题解 - 位运算">
<meta property="og:url" content="https://zhang-shuo-fr.gitee.io/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E4%BD%8D%E8%BF%90%E7%AE%97/index.html">
<meta property="og:site_name" content="Zhang Shuo&#39;blog">
<meta property="og:description" content="Leetcode 题解 - 位运算  Leetcode 题解 - 位运算 0. 原理 1. 统计两个数的二进制表示有多少位不同 2. 数组中唯一一个不重复的元素 3. 找出数组中缺失的那个数 4. 数组中不重复的两个元素 5. 翻转一个数的比特位 6. 不用额外变量交换两个整数 7. 判断一个数是不是 2 的 n 次方 8.  判断一个数是不是 4 的 n 次方 9. 判断一个数的位级表示是否不会">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://zhang-shuo-fr.gitee.io/hexo3/img/18.jpg">
<meta property="article:published_time" content="2021-12-06T09:36:00.000Z">
<meta property="article:modified_time" content="2021-12-10T12:57:38.855Z">
<meta property="article:author" content="Zhang Shuo">
<meta property="article:tag" content="Leetcode题解">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zhang-shuo-fr.gitee.io/hexo3/img/18.jpg"><link rel="shortcut icon" href="/hexo3/img/mao_tou_xiang.jpg"><link rel="canonical" href="https://zhang-shuo-fr.gitee.io/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E4%BD%8D%E8%BF%90%E7%AE%97/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//fonts.googleapis.com" crossorigin=""/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="manifest" href="/hexo3/pwa/manifest.json"/><link rel="apple-touch-icon" sizes="180x180" href="/hexo3/pwa/apple-touch-icon.png"/><link rel="icon" type="image/png" sizes="32x32" href="/hexo3/pwa/32.png"/><link rel="icon" type="image/png" sizes="16x16" href="/hexo3/pwa/16.png"/><link rel="mask-icon" href="/hexo3/pwa/safari-pinned-tab.svg" color="#5bbad5"/><link rel="stylesheet" href="/hexo3/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Titillium+Web&amp;display=swap" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/hexo3/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Leetcode 题解 - 位运算',
  isPost: true,
  isHome: false,
  isHighlightShrink: undefined,
  isToc: true,
  postUpdate: '2021-12-10 20:57:38'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    document.addEventListener('pjax:complete', detectApple)})(window)</script><style type="text/css">#toggle-sidebar {left:100px}</style><meta name="generator" content="Hexo 5.4.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/hexo3/img/mao_tou_xiang.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/hexo3/archives/"><div class="headline">文章</div><div class="length-num">176</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/hexo3/tags/"><div class="headline">标签</div><div class="length-num">45</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/hexo3/categories/"><div class="headline">分类</div><div class="length-num">15</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/hexo3/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 小窝</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/hexo3/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/hexo3/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/hexo3/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/hexo3/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/hexo3/img/18.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/hexo3/">Zhang Shuo'blog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/hexo3/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 小窝</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/hexo3/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/hexo3/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/hexo3/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/hexo3/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Leetcode 题解 - 位运算</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-12-06T09:36:00.000Z" title="发表于 2021-12-06 17:36:00">2021-12-06</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-12-10T12:57:38.855Z" title="更新于 2021-12-10 20:57:38">2021-12-10</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/hexo3/categories/Leetcode%E9%A2%98%E8%A7%A3/">Leetcode题解</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.6k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>11分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Leetcode 题解 - 位运算"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Leetcode-题解-位运算"><a href="#Leetcode-题解-位运算" class="headerlink" title="Leetcode 题解 - 位运算"></a>Leetcode 题解 - 位运算</h1><!-- GFM-TOC -->
<ul>
<li><a href="#leetcode-%E9%A2%98%E8%A7%A3---%E4%BD%8D%E8%BF%90%E7%AE%97">Leetcode 题解 - 位运算</a><ul>
<li><a href="#0-%E5%8E%9F%E7%90%86">0. 原理</a></li>
<li><a href="#1-%E7%BB%9F%E8%AE%A1%E4%B8%A4%E4%B8%AA%E6%95%B0%E7%9A%84%E4%BA%8C%E8%BF%9B%E5%88%B6%E8%A1%A8%E7%A4%BA%E6%9C%89%E5%A4%9A%E5%B0%91%E4%BD%8D%E4%B8%8D%E5%90%8C">1. 统计两个数的二进制表示有多少位不同</a></li>
<li><a href="#2-%E6%95%B0%E7%BB%84%E4%B8%AD%E5%94%AF%E4%B8%80%E4%B8%80%E4%B8%AA%E4%B8%8D%E9%87%8D%E5%A4%8D%E7%9A%84%E5%85%83%E7%B4%A0">2. 数组中唯一一个不重复的元素</a></li>
<li><a href="#3-%E6%89%BE%E5%87%BA%E6%95%B0%E7%BB%84%E4%B8%AD%E7%BC%BA%E5%A4%B1%E7%9A%84%E9%82%A3%E4%B8%AA%E6%95%B0">3. 找出数组中缺失的那个数</a></li>
<li><a href="#4-%E6%95%B0%E7%BB%84%E4%B8%AD%E4%B8%8D%E9%87%8D%E5%A4%8D%E7%9A%84%E4%B8%A4%E4%B8%AA%E5%85%83%E7%B4%A0">4. 数组中不重复的两个元素</a></li>
<li><a href="#5-%E7%BF%BB%E8%BD%AC%E4%B8%80%E4%B8%AA%E6%95%B0%E7%9A%84%E6%AF%94%E7%89%B9%E4%BD%8D">5. 翻转一个数的比特位</a></li>
<li><a href="#6-%E4%B8%8D%E7%94%A8%E9%A2%9D%E5%A4%96%E5%8F%98%E9%87%8F%E4%BA%A4%E6%8D%A2%E4%B8%A4%E4%B8%AA%E6%95%B4%E6%95%B0">6. 不用额外变量交换两个整数</a></li>
<li><a href="#7-%E5%88%A4%E6%96%AD%E4%B8%80%E4%B8%AA%E6%95%B0%E6%98%AF%E4%B8%8D%E6%98%AF-2-%E7%9A%84-n-%E6%AC%A1%E6%96%B9">7. 判断一个数是不是 2 的 n 次方</a></li>
<li><a href="#8--%E5%88%A4%E6%96%AD%E4%B8%80%E4%B8%AA%E6%95%B0%E6%98%AF%E4%B8%8D%E6%98%AF-4-%E7%9A%84-n-%E6%AC%A1%E6%96%B9">8.  判断一个数是不是 4 的 n 次方</a></li>
<li><a href="#9-%E5%88%A4%E6%96%AD%E4%B8%80%E4%B8%AA%E6%95%B0%E7%9A%84%E4%BD%8D%E7%BA%A7%E8%A1%A8%E7%A4%BA%E6%98%AF%E5%90%A6%E4%B8%8D%E4%BC%9A%E5%87%BA%E7%8E%B0%E8%BF%9E%E7%BB%AD%E7%9A%84-0-%E5%92%8C-1">9. 判断一个数的位级表示是否不会出现连续的 0 和 1</a></li>
<li><a href="#10-%E6%B1%82%E4%B8%80%E4%B8%AA%E6%95%B0%E7%9A%84%E8%A1%A5%E7%A0%81">10. 求一个数的补码</a></li>
<li><a href="#11-%E5%AE%9E%E7%8E%B0%E6%95%B4%E6%95%B0%E7%9A%84%E5%8A%A0%E6%B3%95">11. 实现整数的加法</a></li>
<li><a href="#12-%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%95%B0%E7%BB%84%E6%9C%80%E5%A4%A7%E4%B9%98%E7%A7%AF">12. 字符串数组最大乘积</a></li>
<li><a href="#13-%E7%BB%9F%E8%AE%A1%E4%BB%8E-0-~-n-%E6%AF%8F%E4%B8%AA%E6%95%B0%E7%9A%84%E4%BA%8C%E8%BF%9B%E5%88%B6%E8%A1%A8%E7%A4%BA%E4%B8%AD-1-%E7%9A%84%E4%B8%AA%E6%95%B0">13. 统计从 0 ~ n 每个数的二进制表示中 1 的个数</a><!-- GFM-TOC --></li>
</ul>
</li>
</ul>
<h2 id="0-原理"><a href="#0-原理" class="headerlink" title="0. 原理"></a>0. 原理</h2><p><strong>基本原理</strong> </p>
<p>0s 表示一串 0，1s 表示一串 1。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">x ^ 0s = x      x &amp; 0s = 0      x | 0s = x</span><br><span class="line">x ^ 1s = ~x     x &amp; 1s = x      x | 1s = 1s</span><br><span class="line">x ^ x = 0       x &amp; x = x       x | x = x</span><br></pre></td></tr></table></figure>

<p>利用 x ^ 1s = ~x 的特点，可以将一个数的位级表示翻转；利用 x ^ x = 0 的特点，可以将三个数中重复的两个数去除，只留下另一个数。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">1^1^2 = 2</span><br></pre></td></tr></table></figure>

<p>利用 x &amp; 0s = 0 和 x &amp; 1s = x 的特点，可以实现掩码操作。一个数 num 与 mask：00111100 进行位与操作，只保留 num 中与 mask 的 1 部分相对应的位。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">01011011 &amp;</span><br><span class="line">00111100</span><br><span class="line">--------</span><br><span class="line">00011000</span><br></pre></td></tr></table></figure>

<p>利用 x | 0s = x 和 x | 1s = 1s 的特点，可以实现设值操作。一个数 num 与 mask：00111100 进行位或操作，将 num 中与 mask 的 1 部分相对应的位都设置为 1。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">01011011 |</span><br><span class="line">00111100</span><br><span class="line">--------</span><br><span class="line">01111111</span><br></pre></td></tr></table></figure>

<p><strong>位与运算技巧</strong> </p>
<p>n&amp;(n-1) 去除 n 的位级表示中最低的那一位 1。例如对于二进制表示 01011011，减去 1 得到 01011010，这两个数相与得到 01011010。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">01011011 &amp;</span><br><span class="line">01011010</span><br><span class="line">--------</span><br><span class="line">01011010</span><br></pre></td></tr></table></figure>

<p>n&amp;(-n) 得到 n 的位级表示中最低的那一位 1。-n 得到 n 的反码加 1，也就是 -n=~n+1。例如对于二进制表示 10110100，-n 得到 01001100，相与得到 00000100。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">10110100 &amp;</span><br><span class="line">01001100</span><br><span class="line">--------</span><br><span class="line">00000100</span><br></pre></td></tr></table></figure>

<p>n-(n&amp;(-n)) 则可以去除 n 的位级表示中最低的那一位 1，和 n&amp;(n-1) 效果一样。</p>
<p><strong>移位运算</strong> </p>
<p>\&gt;\&gt; n 为算术右移，相当于除以 2n，例如 -7 \&gt;\&gt; 2 = -2。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">11111111111111111111111111111001  &gt;&gt; 2</span><br><span class="line">--------</span><br><span class="line">11111111111111111111111111111110</span><br></pre></td></tr></table></figure>

<p>\&gt;\&gt;\&gt; n 为无符号右移，左边会补上 0。例如 -7 \&gt;\&gt;\&gt; 2 = 1073741822。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">11111111111111111111111111111001  &gt;&gt;&gt; 2</span><br><span class="line">--------</span><br><span class="line">00111111111111111111111111111111</span><br></pre></td></tr></table></figure>

<p>&lt;&lt; n 为算术左移，相当于乘以 2n。-7 &lt;&lt; 2 = -28。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">11111111111111111111111111111001  &lt;&lt; 2</span><br><span class="line">--------</span><br><span class="line">11111111111111111111111111100100</span><br></pre></td></tr></table></figure>

<p><strong>mask 计算</strong> </p>
<p>要获取 111111111，将 0 取反即可，~0。</p>
<p>要得到只有第 i 位为 1 的 mask，将 1 向左移动 i-1 位即可，1&lt;&lt;(i-1) 。例如 1&lt;&lt;4 得到只有第 5 位为 1 的 mask ：00010000。</p>
<p>要得到 1 到 i 位为 1 的 mask，(1&lt;&lt;i)-1 即可，例如将 (1&lt;&lt;4)-1 = 00010000-1 = 00001111。</p>
<p>要得到 1 到 i 位为 0 的 mask，只需将 1 到 i 位为 1 的 mask 取反，即 ~((1&lt;&lt;i)-1)。</p>
<p><strong>Java 中的位操作</strong>  </p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">static int Integer.bitCount();           // 统计 1 的数量</span><br><span class="line">static int Integer.highestOneBit();      // 获得最高位</span><br><span class="line">static String toBinaryString(int i);     // 转换为二进制表示的字符串</span><br></pre></td></tr></table></figure>

<h2 id="1-统计两个数的二进制表示有多少位不同"><a href="#1-统计两个数的二进制表示有多少位不同" class="headerlink" title="1. 统计两个数的二进制表示有多少位不同"></a>1. 统计两个数的二进制表示有多少位不同</h2><ol start="461">
<li>Hamming Distance (Easy)</li>
</ol>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/hamming-distance/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/hamming-distance/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input: x = 1, y = 4</span><br><span class="line"></span><br><span class="line">Output: 2</span><br><span class="line"></span><br><span class="line">Explanation:</span><br><span class="line">1   (0 0 0 1)</span><br><span class="line">4   (0 1 0 0)</span><br><span class="line">       ↑   ↑</span><br><span class="line"></span><br><span class="line">The above arrows point to positions where the corresponding bits are different.</span><br></pre></td></tr></table></figure>

<p>对两个数进行异或操作，位级表示不同的那一位为 1，统计有多少个 1 即可。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">hammingDistance</span><span class="params">(<span class="keyword">int</span> x, <span class="keyword">int</span> y)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> z = x ^ y;</span><br><span class="line">    <span class="keyword">int</span> cnt = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">while</span>(z != <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> ((z &amp; <span class="number">1</span>) == <span class="number">1</span>) cnt++;</span><br><span class="line">        z = z &gt;&gt; <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> cnt;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>使用 z&amp;(z-1) 去除 z 位级表示最低的那一位。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">hammingDistance</span><span class="params">(<span class="keyword">int</span> x, <span class="keyword">int</span> y)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> z = x ^ y;</span><br><span class="line">    <span class="keyword">int</span> cnt = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">while</span> (z != <span class="number">0</span>) &#123;</span><br><span class="line">        z &amp;= (z - <span class="number">1</span>);</span><br><span class="line">        cnt++;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> cnt;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以使用 Integer.bitcount() 来统计 1 个的个数。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">hammingDistance</span><span class="params">(<span class="keyword">int</span> x, <span class="keyword">int</span> y)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> Integer.bitCount(x ^ y);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="2-数组中唯一一个不重复的元素"><a href="#2-数组中唯一一个不重复的元素" class="headerlink" title="2. 数组中唯一一个不重复的元素"></a>2. 数组中唯一一个不重复的元素</h2><p>136. Single Number (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/single-number/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/single-number/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input: [4,1,2,1,2]</span><br><span class="line">Output: 4</span><br></pre></td></tr></table></figure>

<p>两个相同的数异或的结果为 0，对所有数进行异或操作，最后的结果就是单独出现的那个数。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">singleNumber</span><span class="params">(<span class="keyword">int</span>[] nums)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> ret = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> n : nums) ret = ret ^ n;</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="3-找出数组中缺失的那个数"><a href="#3-找出数组中缺失的那个数" class="headerlink" title="3. 找出数组中缺失的那个数"></a>3. 找出数组中缺失的那个数</h2><p>268. Missing Number (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/missing-number/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/missing-number/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input: [3,0,1]</span><br><span class="line">Output: 2</span><br></pre></td></tr></table></figure>

<p>题目描述：数组元素在 0-n 之间，但是有一个数是缺失的，要求找到这个缺失的数。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">missingNumber</span><span class="params">(<span class="keyword">int</span>[] nums)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> ret = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; nums.length; i++) &#123;</span><br><span class="line">        ret = ret ^ i ^ nums[i];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ret ^ nums.length;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="4-数组中不重复的两个元素"><a href="#4-数组中不重复的两个元素" class="headerlink" title="4. 数组中不重复的两个元素"></a>4. 数组中不重复的两个元素</h2><p>260. Single Number III (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/single-number-iii/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/single-number-iii/description/">力扣</a></p>
<p>两个不相等的元素在位级表示上必定会有一位存在不同。</p>
<p>将数组的所有元素异或得到的结果为不存在重复的两个元素异或的结果。</p>
<p>diff &amp;= -diff 得到出 diff 最右侧不为 0 的位，也就是不存在重复的两个元素在位级表示上最右侧不同的那一位，利用这一位就可以将两个元素区分开来。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">int</span>[] singleNumber(<span class="keyword">int</span>[] nums) &#123;</span><br><span class="line">    <span class="keyword">int</span> diff = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> num : nums) diff ^= num;</span><br><span class="line">    diff &amp;= -diff;  <span class="comment">// 得到最右一位</span></span><br><span class="line">    <span class="keyword">int</span>[] ret = <span class="keyword">new</span> <span class="keyword">int</span>[<span class="number">2</span>];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> num : nums) &#123;</span><br><span class="line">        <span class="keyword">if</span> ((num &amp; diff) == <span class="number">0</span>) ret[<span class="number">0</span>] ^= num;</span><br><span class="line">        <span class="keyword">else</span> ret[<span class="number">1</span>] ^= num;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="5-翻转一个数的比特位"><a href="#5-翻转一个数的比特位" class="headerlink" title="5. 翻转一个数的比特位"></a>5. 翻转一个数的比特位</h2><p>190. Reverse Bits (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/reverse-bits/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/reverse-bits/description/">力扣</a></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">reverseBits</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> ret = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">32</span>; i++) &#123;</span><br><span class="line">        ret &lt;&lt;= <span class="number">1</span>;</span><br><span class="line">        ret |= (n &amp; <span class="number">1</span>);</span><br><span class="line">        n &gt;&gt;&gt;= <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果该函数需要被调用很多次，可以将 int 拆成 4 个 byte，然后缓存 byte 对应的比特位翻转，最后再拼接起来。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> Map&lt;Byte, Integer&gt; cache = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">reverseBits</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> ret = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">4</span>; i++) &#123;</span><br><span class="line">        ret &lt;&lt;= <span class="number">8</span>;</span><br><span class="line">        ret |= reverseByte((<span class="keyword">byte</span>) (n &amp; <span class="number">0b11111111</span>));</span><br><span class="line">        n &gt;&gt;= <span class="number">8</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">reverseByte</span><span class="params">(<span class="keyword">byte</span> b)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (cache.containsKey(b)) <span class="keyword">return</span> cache.get(b);</span><br><span class="line">    <span class="keyword">int</span> ret = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">byte</span> t = b;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">8</span>; i++) &#123;</span><br><span class="line">        ret &lt;&lt;= <span class="number">1</span>;</span><br><span class="line">        ret |= t &amp; <span class="number">1</span>;</span><br><span class="line">        t &gt;&gt;= <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    cache.put(b, ret);</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="6-不用额外变量交换两个整数"><a href="#6-不用额外变量交换两个整数" class="headerlink" title="6. 不用额外变量交换两个整数"></a>6. 不用额外变量交换两个整数</h2><p><a href="#">程序员代码面试指南 ：P317</a></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">a = a ^ b;</span><br><span class="line">b = a ^ b;</span><br><span class="line">a = a ^ b;</span><br></pre></td></tr></table></figure>

<h2 id="7-判断一个数是不是-2-的-n-次方"><a href="#7-判断一个数是不是-2-的-n-次方" class="headerlink" title="7. 判断一个数是不是 2 的 n 次方"></a>7. 判断一个数是不是 2 的 n 次方</h2><p>231. Power of Two (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/power-of-two/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/power-of-two/description/">力扣</a></p>
<p>二进制表示只有一个 1 存在。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isPowerOfTwo</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> n &gt; <span class="number">0</span> &amp;&amp; Integer.bitCount(n) == <span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>利用 1000 &amp; 0111 == 0 这种性质，得到以下解法：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isPowerOfTwo</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> n &gt; <span class="number">0</span> &amp;&amp; (n &amp; (n - <span class="number">1</span>)) == <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="8-判断一个数是不是-4-的-n-次方"><a href="#8-判断一个数是不是-4-的-n-次方" class="headerlink" title="8.  判断一个数是不是 4 的 n 次方"></a>8.  判断一个数是不是 4 的 n 次方</h2><p>342. Power of Four (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/power-of-four/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/power-of-four/">力扣</a></p>
<p>这种数在二进制表示中有且只有一个奇数位为 1，例如 16（10000）。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isPowerOfFour</span><span class="params">(<span class="keyword">int</span> num)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> num &gt; <span class="number">0</span> &amp;&amp; (num &amp; (num - <span class="number">1</span>)) == <span class="number">0</span> &amp;&amp; (num &amp; <span class="number">0b01010101010101010101010101010101</span>) != <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>也可以使用正则表达式进行匹配。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isPowerOfFour</span><span class="params">(<span class="keyword">int</span> num)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> Integer.toString(num, <span class="number">4</span>).matches(<span class="string">&quot;10*&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="9-判断一个数的位级表示是否不会出现连续的-0-和-1"><a href="#9-判断一个数的位级表示是否不会出现连续的-0-和-1" class="headerlink" title="9. 判断一个数的位级表示是否不会出现连续的 0 和 1"></a>9. 判断一个数的位级表示是否不会出现连续的 0 和 1</h2><p>693. Binary Number with Alternating Bits (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/binary-number-with-alternating-bits/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/binary-number-with-alternating-bits/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input: 10</span><br><span class="line">Output: True</span><br><span class="line">Explanation:</span><br><span class="line">The binary representation of 10 is: 1010.</span><br><span class="line"></span><br><span class="line">Input: 11</span><br><span class="line">Output: False</span><br><span class="line">Explanation:</span><br><span class="line">The binary representation of 11 is: 1011.</span><br></pre></td></tr></table></figure>

<p>对于 1010 这种位级表示的数，把它向右移动 1 位得到 101，这两个数每个位都不同，因此异或得到的结果为 1111。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">hasAlternatingBits</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> a = (n ^ (n &gt;&gt; <span class="number">1</span>));</span><br><span class="line">    <span class="keyword">return</span> (a &amp; (a + <span class="number">1</span>)) == <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="10-求一个数的补码"><a href="#10-求一个数的补码" class="headerlink" title="10. 求一个数的补码"></a>10. 求一个数的补码</h2><p>476. Number Complement (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/number-complement/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/number-complement/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input: 5</span><br><span class="line">Output: 2</span><br><span class="line">Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.</span><br></pre></td></tr></table></figure>

<p>题目描述：不考虑二进制表示中的首 0 部分。</p>
<p>对于 00000101，要求补码可以将它与 00000111 进行异或操作。那么问题就转换为求掩码 00000111。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">findComplement</span><span class="params">(<span class="keyword">int</span> num)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (num == <span class="number">0</span>) <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">int</span> mask = <span class="number">1</span> &lt;&lt; <span class="number">30</span>;</span><br><span class="line">    <span class="keyword">while</span> ((num &amp; mask) == <span class="number">0</span>) mask &gt;&gt;= <span class="number">1</span>;</span><br><span class="line">    mask = (mask &lt;&lt; <span class="number">1</span>) - <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">return</span> num ^ mask;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以利用 Java 的 Integer.highestOneBit() 方法来获得含有首 1 的数。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">findComplement</span><span class="params">(<span class="keyword">int</span> num)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (num == <span class="number">0</span>) <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">int</span> mask = Integer.highestOneBit(num);</span><br><span class="line">    mask = (mask &lt;&lt; <span class="number">1</span>) - <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">return</span> num ^ mask;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>对于 10000000 这样的数要扩展成 11111111，可以利用以下方法：</p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">mask |= mask &gt;&gt; 1    11000000</span><br><span class="line">mask |= mask &gt;&gt; 2    11110000</span><br><span class="line">mask |= mask &gt;&gt; 4    11111111</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">findComplement</span><span class="params">(<span class="keyword">int</span> num)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> mask = num;</span><br><span class="line">    mask |= mask &gt;&gt; <span class="number">1</span>;</span><br><span class="line">    mask |= mask &gt;&gt; <span class="number">2</span>;</span><br><span class="line">    mask |= mask &gt;&gt; <span class="number">4</span>;</span><br><span class="line">    mask |= mask &gt;&gt; <span class="number">8</span>;</span><br><span class="line">    mask |= mask &gt;&gt; <span class="number">16</span>;</span><br><span class="line">    <span class="keyword">return</span> (mask ^ num);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="11-实现整数的加法"><a href="#11-实现整数的加法" class="headerlink" title="11. 实现整数的加法"></a>11. 实现整数的加法</h2><p>371. Sum of Two Integers (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/sum-of-two-integers/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/sum-of-two-integers/description/">力扣</a></p>
<p>a ^ b 表示没有考虑进位的情况下两数的和，(a &amp; b) &lt;&lt; 1 就是进位。</p>
<p>递归会终止的原因是 (a &amp; b) &lt;&lt; 1 最右边会多一个 0，那么继续递归，进位最右边的 0 会慢慢增多，最后进位会变为 0，递归终止。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getSum</span><span class="params">(<span class="keyword">int</span> a, <span class="keyword">int</span> b)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> b == <span class="number">0</span> ? a : getSum((a ^ b), (a &amp; b) &lt;&lt; <span class="number">1</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="12-字符串数组最大乘积"><a href="#12-字符串数组最大乘积" class="headerlink" title="12. 字符串数组最大乘积"></a>12. 字符串数组最大乘积</h2><p>318. Maximum Product of Word Lengths (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/maximum-product-of-word-lengths/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/maximum-product-of-word-lengths/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Given [&quot;abcw&quot;, &quot;baz&quot;, &quot;foo&quot;, &quot;bar&quot;, &quot;xtfn&quot;, &quot;abcdef&quot;]</span><br><span class="line">Return 16</span><br><span class="line">The two words can be &quot;abcw&quot;, &quot;xtfn&quot;.</span><br></pre></td></tr></table></figure>

<p>题目描述：字符串数组的字符串只含有小写字符。求解字符串数组中两个字符串长度的最大乘积，要求这两个字符串不能含有相同字符。</p>
<p>本题主要问题是判断两个字符串是否含相同字符，由于字符串只含有小写字符，总共 26 位，因此可以用一个 32 位的整数来存储每个字符是否出现过。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">maxProduct</span><span class="params">(String[] words)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> n = words.length;</span><br><span class="line">    <span class="keyword">int</span>[] val = <span class="keyword">new</span> <span class="keyword">int</span>[n];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">char</span> c : words[i].toCharArray()) &#123;</span><br><span class="line">            val[i] |= <span class="number">1</span> &lt;&lt; (c - <span class="string">&#x27;a&#x27;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">int</span> ret = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = i + <span class="number">1</span>; j &lt; n; j++) &#123;</span><br><span class="line">            <span class="keyword">if</span> ((val[i] &amp; val[j]) == <span class="number">0</span>) &#123;</span><br><span class="line">                ret = Math.max(ret, words[i].length() * words[j].length());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="13-统计从-0-n-每个数的二进制表示中-1-的个数"><a href="#13-统计从-0-n-每个数的二进制表示中-1-的个数" class="headerlink" title="13. 统计从 0 ~ n 每个数的二进制表示中 1 的个数"></a>13. 统计从 0 ~ n 每个数的二进制表示中 1 的个数</h2><p>338. Counting Bits (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/counting-bits/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/counting-bits/description/">力扣</a></p>
<p>对于数字 6(110)，它可以看成是 4(100) 再加一个 2(10)，因此 dp[i] = dp[i&amp;(i-1)] + 1;</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">int</span>[] countBits(<span class="keyword">int</span> num) &#123;</span><br><span class="line">    <span class="keyword">int</span>[] ret = <span class="keyword">new</span> <span class="keyword">int</span>[num + <span class="number">1</span>];</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= num; i++)&#123;</span><br><span class="line">        ret[i] = ret[i&amp;(i-<span class="number">1</span>)] + <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Zhang Shuo</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://zhang-shuo-fr.gitee.io/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E4%BD%8D%E8%BF%90%E7%AE%97/">https://zhang-shuo-fr.gitee.io/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E4%BD%8D%E8%BF%90%E7%AE%97/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://zhang-shuo-fr.gitee.io/hexo3" target="_blank">Zhang Shuo'blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/hexo3/tags/Leetcode%E9%A2%98%E8%A7%A3/">Leetcode题解</a></div><div class="post_share"><div class="social-share" data-image="/hexo3/img/18.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/hexo3/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/hexo3/img/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/hexo3/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/hexo3/img/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E5%88%86%E6%B2%BB/"><img class="prev-cover" src= "" data-lazy-src="/hexo3/img/8.jpg" onerror="onerror=null;src='/hexo3/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Leetcode 题解 - 分治</div></div></a></div><div class="next-post pull-right"><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE/"><img class="next-cover" src= "" data-lazy-src="/hexo3/img/1.jpg" onerror="onerror=null;src='/hexo3/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Leetcode 题解 - 二分查找</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE/" title="Leetcode 题解 - 二分查找"><img class="cover" src= "" data-lazy-src="/hexo3/img/1.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 二分查找</div></div></a></div><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E5%88%86%E6%B2%BB/" title="Leetcode 题解 - 分治"><img class="cover" src= "" data-lazy-src="/hexo3/img/8.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 分治</div></div></a></div><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E5%8F%8C%E6%8C%87%E9%92%88/" title="Leetcode 题解 - 双指针"><img class="cover" src= "" data-lazy-src="/hexo3/img/1.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 双指针</div></div></a></div><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E5%93%88%E5%B8%8C%E8%A1%A8/" title="Leetcode 题解 - 哈希表"><img class="cover" src= "" data-lazy-src="/hexo3/img/12.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 哈希表</div></div></a></div><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E5%9B%BE/" title="Leetcode 题解 - 图"><img class="cover" src= "" data-lazy-src="/hexo3/img/19.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 图</div></div></a></div><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E6%8E%92%E5%BA%8F/" title="Leetcode 题解 - 排序"><img class="cover" src= "" data-lazy-src="/hexo3/img/7.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 排序</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Leetcode-%E9%A2%98%E8%A7%A3-%E4%BD%8D%E8%BF%90%E7%AE%97"><span class="toc-number">1.</span> <span class="toc-text">Leetcode 题解 - 位运算</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#0-%E5%8E%9F%E7%90%86"><span class="toc-number">1.1.</span> <span class="toc-text">0. 原理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E7%BB%9F%E8%AE%A1%E4%B8%A4%E4%B8%AA%E6%95%B0%E7%9A%84%E4%BA%8C%E8%BF%9B%E5%88%B6%E8%A1%A8%E7%A4%BA%E6%9C%89%E5%A4%9A%E5%B0%91%E4%BD%8D%E4%B8%8D%E5%90%8C"><span class="toc-number">1.2.</span> <span class="toc-text">1. 统计两个数的二进制表示有多少位不同</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E6%95%B0%E7%BB%84%E4%B8%AD%E5%94%AF%E4%B8%80%E4%B8%80%E4%B8%AA%E4%B8%8D%E9%87%8D%E5%A4%8D%E7%9A%84%E5%85%83%E7%B4%A0"><span class="toc-number">1.3.</span> <span class="toc-text">2. 数组中唯一一个不重复的元素</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-%E6%89%BE%E5%87%BA%E6%95%B0%E7%BB%84%E4%B8%AD%E7%BC%BA%E5%A4%B1%E7%9A%84%E9%82%A3%E4%B8%AA%E6%95%B0"><span class="toc-number">1.4.</span> <span class="toc-text">3. 找出数组中缺失的那个数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-%E6%95%B0%E7%BB%84%E4%B8%AD%E4%B8%8D%E9%87%8D%E5%A4%8D%E7%9A%84%E4%B8%A4%E4%B8%AA%E5%85%83%E7%B4%A0"><span class="toc-number">1.5.</span> <span class="toc-text">4. 数组中不重复的两个元素</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-%E7%BF%BB%E8%BD%AC%E4%B8%80%E4%B8%AA%E6%95%B0%E7%9A%84%E6%AF%94%E7%89%B9%E4%BD%8D"><span class="toc-number">1.6.</span> <span class="toc-text">5. 翻转一个数的比特位</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-%E4%B8%8D%E7%94%A8%E9%A2%9D%E5%A4%96%E5%8F%98%E9%87%8F%E4%BA%A4%E6%8D%A2%E4%B8%A4%E4%B8%AA%E6%95%B4%E6%95%B0"><span class="toc-number">1.7.</span> <span class="toc-text">6. 不用额外变量交换两个整数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7-%E5%88%A4%E6%96%AD%E4%B8%80%E4%B8%AA%E6%95%B0%E6%98%AF%E4%B8%8D%E6%98%AF-2-%E7%9A%84-n-%E6%AC%A1%E6%96%B9"><span class="toc-number">1.8.</span> <span class="toc-text">7. 判断一个数是不是 2 的 n 次方</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#8-%E5%88%A4%E6%96%AD%E4%B8%80%E4%B8%AA%E6%95%B0%E6%98%AF%E4%B8%8D%E6%98%AF-4-%E7%9A%84-n-%E6%AC%A1%E6%96%B9"><span class="toc-number">1.9.</span> <span class="toc-text">8.  判断一个数是不是 4 的 n 次方</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#9-%E5%88%A4%E6%96%AD%E4%B8%80%E4%B8%AA%E6%95%B0%E7%9A%84%E4%BD%8D%E7%BA%A7%E8%A1%A8%E7%A4%BA%E6%98%AF%E5%90%A6%E4%B8%8D%E4%BC%9A%E5%87%BA%E7%8E%B0%E8%BF%9E%E7%BB%AD%E7%9A%84-0-%E5%92%8C-1"><span class="toc-number">1.10.</span> <span class="toc-text">9. 判断一个数的位级表示是否不会出现连续的 0 和 1</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#10-%E6%B1%82%E4%B8%80%E4%B8%AA%E6%95%B0%E7%9A%84%E8%A1%A5%E7%A0%81"><span class="toc-number">1.11.</span> <span class="toc-text">10. 求一个数的补码</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#11-%E5%AE%9E%E7%8E%B0%E6%95%B4%E6%95%B0%E7%9A%84%E5%8A%A0%E6%B3%95"><span class="toc-number">1.12.</span> <span class="toc-text">11. 实现整数的加法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#12-%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%95%B0%E7%BB%84%E6%9C%80%E5%A4%A7%E4%B9%98%E7%A7%AF"><span class="toc-number">1.13.</span> <span class="toc-text">12. 字符串数组最大乘积</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#13-%E7%BB%9F%E8%AE%A1%E4%BB%8E-0-n-%E6%AF%8F%E4%B8%AA%E6%95%B0%E7%9A%84%E4%BA%8C%E8%BF%9B%E5%88%B6%E8%A1%A8%E7%A4%BA%E4%B8%AD-1-%E7%9A%84%E4%B8%AA%E6%95%B0"><span class="toc-number">1.14.</span> <span class="toc-text">13. 统计从 0 ~ n 每个数的二进制表示中 1 的个数</span></a></li></ol></li></ol></div></div></div></div></main><footer id="footer" style="background-image: url('/hexo3/img/18.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By Zhang Shuo</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">Hi, welcome to my blog!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">簡</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/hexo3/js/utils.js"></script><script src="/hexo3/js/main.js"></script><script src="/hexo3/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/hexo3/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"></div><div class="aplayer no-destroy" data-id="000PeZCQ1i4XVs" data-server="tencent" data-type="artist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-preload="none" data-autoplay="true" muted></div><script defer="defer" id="fluttering_ribbon" mobile="true" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="true" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = true;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="true"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.removeEventListener('scroll', window.tocScrollFn)
  window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>